package vivek.project.pocketmoney.mutualfund.model.utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import mx.collections.ArrayCollection;
	import mx.formatters.NumberFormatter;
	import vivek.project.pocketmoney.common.CommonData;
	import vivek.project.pocketmoney.common.logger.PMLogger;
	import vivek.project.pocketmoney.common.utils.StringUtils;
	import vivek.project.pocketmoney.mutualfund.model.MutualFundDataCache;
	import vivek.project.pocketmoney.mutualfund.model.MutualFundModel;

	public class GoogleAppMutualFundPriceUpdateWorker extends EventDispatcher
	{
		private var URLData:String=new String();
		private var endDate:Date=new Date();
		private var giantCap:String=new String();
		private var histDate:Date=new Date();
		private var largeCap:String=new String();
		private var mfid:int=0;
		private var midCap:String=new String();
		private var mutualFundModel:MutualFundModel=MutualFundModel.getInstance();
		private var navDate:String=new String();
		private const navUrl:String="http://mfindiahistory.appspot.com/serveNAV?";
		private var navValue:String=new String();
		private var numberFormatter:NumberFormatter=new NumberFormatter();
		private var paramColl:ArrayCollection;
		private const portfolioUrl:String="http://valueresearchonline.com/funds/portfoliovr.asp?schemecode=";
		private var schemeControl:ArrayCollection=MutualFundDataCache.schemeControl;
		private var smallCap:String=new String();
		private var startDate:Date=new Date();
		private var tinyCap:String=new String();
		private var urlReq:URLRequest=new URLRequest(navUrl);

		public function getNAVAllSchemes(schemes:ArrayCollection):void
		{
			for each (var mfObj:Object in schemeControl)
			{
				var _startDate:Date=mfObj.sm_lastupdated;
				getNAVValue(mfObj.sm_schemeid, mfObj.sm_lastupdated, new Date());
			}
		}

		public function getNAVData(mfScheme:Object, _startDate:Date, _endDate:Date):void
		{
			getNAVValue(mfScheme.sm_schemeid, _startDate, _endDate);
			//getHistoricNAVValue(mfScheme.sm_schemeid);
		}

		private function doEvent(evt:Event):void
		{
			switch (evt.type)
			{
				case Event.COMPLETE: /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
					var ldr:URLLoader=evt.currentTarget as URLLoader;
					URLData=ldr.data;
					//getLatestNAVValue();
					var values:Array=URLData.split("\n");
					var array:Array=new Array();
					for (var i:int; i < values.length - 1; i++)
					{
						var dataParts:Array=values[i].toString().split(',');
						var date:Date=new Date();
						//date.setMilliseconds(dataParts[1]);
						var object:Object=new Object();
						object.mfid=mfid;
						object.mfValue=dataParts[3];
						object.navDate=dataParts[2];
						array.push(object)
							//mutualFundModel.addMFNAVValueToHistory(values[0],StringUtils.trimSpecialChar(values[2]),CommonData.getDateFormatterSlash().format(startDate));
					}
					dispatchEvent(new Event("UpdateCompletedSuccessFully"));
					mutualFundModel.addMFNAVBlockToHistory(array);
					break;
				case IOErrorEvent.IO_ERROR:
				{
					//PMLogger.logMisc("MFDATAFETCH", evt.toString(), mfid + startDate.toDateString() + endDate.toDateString());
					trace(mfid + evt.toString() + ", Could not be updated, From : " + startDate.toDateString() + " End Date : " + startDate.toDateString());
					dispatchEvent(new Event("UpdateCompletedWithError"));
					break;
				}
			}
		}

		private function doPortfolioEvent(evt:Event):void
		{
			switch (evt.type)
			{
				case Event.COMPLETE: /* If the load was successful, create a URLVariables object from the URLLoader.data property and populate the paramColl ArrayCollection object. */
					var ldr:URLLoader=evt.currentTarget as URLLoader;
					URLData=ldr.data;
					getMktCap();
					mutualFundModel.updatePortfolioType(mfid, giantCap, largeCap, midCap, smallCap, tinyCap);
					dispatchEvent(new Event("UpdateCompletedSuccessFully"));
					//mutualFundModel.addMFNAVValueToDatabase(mfid,navValue,navDate);
					break;
				case IOErrorEvent.IO_ERROR:
				{
					trace(evt.currentTarget.toString());
					dispatchEvent(new Event("UpdateCompletedWithError"));
					break;
				}
			}
		}

		private function getMktCap():void
		{
			try
			{
				giantCap=StringUtils.trimSpecialChar(StringUtils.stripBetweenNOccurance(URLData, "<font size=\"1\" class=\"right\">", 2, "</font>"));
				largeCap=StringUtils.trimSpecialChar(StringUtils.stripBetweenNOccurance(URLData, "<font size=\"1\" class=\"right\">", 3, "</font>"));
				midCap=StringUtils.trimSpecialChar(StringUtils.stripBetweenNOccurance(URLData, "<font size=\"1\" class=\"right\">", 4, "</font>"));
				smallCap=StringUtils.trimSpecialChar(StringUtils.stripBetweenNOccurance(URLData, "<font size=\"1\" class=\"right\">", 5, "</font>"));
				tinyCap=StringUtils.trimSpecialChar(StringUtils.stripBetweenNOccurance(URLData, "<font size=\"1\" class=\"right\">", 6, "</font>"));
				if (tinyCap == "")
					tinyCap="0.00";
				if (smallCap == "")
					smallCap="0.00";
				if (giantCap == "")
					giantCap="0.00";
				if (largeCap == "")
					largeCap="0.00";
				if (midCap == "")
					midCap="0.00";
			}
			catch (e:Error)
			{
				tinyCap="0.00";
				smallCap="0.00";
				giantCap="0.00";
				midCap="0.00";
			}
		}

		private function getNAVValue(schemeid:int, _startDate:Date, _endDate:Date):void
		{
			this.mfid=schemeid;
			var textLoader:URLLoader=new URLLoader();
			//startDate=&endDate=&
			var variables:URLVariables=new URLVariables();
			variables.schemeId=schemeid;
			//startDate=DateUtils.dateAdd("date",-1,startDate);
			variables.startDate=CommonData.getDateFormatterSlash().format(_startDate);
			variables.endDate=CommonData.getDateFormatterSlash().format(_endDate);
			var textReq:URLRequest=new URLRequest(navUrl + "schemeId=" + schemeid + "&startDate=" + variables.startDate + "&endDate=" + variables.endDate);
			textReq.method=URLRequestMethod.GET;
			//textReq.data = variables;
			textLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doEvent);
			textLoader.addEventListener(IOErrorEvent.IO_ERROR, doEvent);
			textLoader.addEventListener(Event.COMPLETE, doEvent);
			textLoader.load(textReq);
		/*if (MutualFundModel.getSchemeForId(schemeid).sm_schemetype == MutualFundConstants.EQUITY)
		   {
		   var textLoader1:URLLoader=new URLLoader();
		   var textReq1:URLRequest=new URLRequest(portfolioUrl + schemeid);
		   textLoader1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, doPortfolioEvent);
		   textLoader1.addEventListener(IOErrorEvent.IO_ERROR, doPortfolioEvent);
		   textLoader1.addEventListener(Event.COMPLETE, doPortfolioEvent);
		   textLoader1.load(textReq1);
		   }
		   else
		   {
		   dispatchEvent(new Event("UpdateCompletedSuccessFully"));
		 }*/
		}
	}
}